package com.naspan.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.naspan.common.Enum.VerifyRegexEnum;
import com.naspan.common.Result;
import com.naspan.common.annotation.GlobalInterceptor;
import com.naspan.common.annotation.VerifyParam;
import com.naspan.common.config.AppConfig;
import com.naspan.common.constants.Constants;
import com.naspan.common.exception.bizExceptionHandle;
import com.naspan.entity.dto.RegisterDto;
import com.naspan.entity.dto.UserSpaceDto;
import com.naspan.entity.po.User;
import com.naspan.entity.vo.LoginUserVo;
import com.naspan.service.UserService;
import com.naspan.utils.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

@RestController
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private AppConfig appConfig;
    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @PostMapping("/register")
    @GlobalInterceptor(checkParam = true, checkLogin = false)
    public Result register(HttpSession session, @VerifyParam RegisterDto registerDto) {
        String code = (String) session.getAttribute(Constants.REGISTER_CODE + "key");
        if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(registerDto.getCheckCode())) {
            throw new bizExceptionHandle("验证码错误，请重新输入");
        }
        return userService.registerHandle(registerDto);
    }

    @GetMapping("/login")
    @GlobalInterceptor(checkParam = true, checkLogin = false)
    public Result login(HttpSession session,
                        @VerifyParam(require = true, regex = VerifyRegexEnum.EMAIL) String email,
                        @VerifyParam(require = true) String password,
                        @VerifyParam(require = true) String checkCode) {
        String code = (String) session.getAttribute(Constants.REGISTER_CODE + "key");
        if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(checkCode)) {
            throw new bizExceptionHandle("验证码错误，请重新输入");
        }
        LoginUserVo loginUserVo = userService.loginHandle(email, password, checkCode);
        ServletUtils.setUser(loginUserVo);
        return Result.success(loginUserVo);
    }

    @PostMapping("/resetPassword")
    @GlobalInterceptor(checkParam = true)
    public void resetPassword(HttpSession session,
                              @VerifyParam(require = true, regex = VerifyRegexEnum.EMAIL) String email,
                              @VerifyParam(require = true) String emailCode,
                              @VerifyParam(require = true) String password,
                              @VerifyParam(require = true) String checkCode) {
        String code = (String) session.getAttribute(Constants.REGISTER_CODE + "key");
        if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(checkCode)) {
            throw new bizExceptionHandle("验证码错误，请重新输入");
        }
        userService.resetPassword(email, emailCode, password);
    }

    @GetMapping("/logout")
    public Result login(HttpSession session) {
        session.invalidate();
        return Result.success("退出成功");
    }

    @GetMapping("/getAvatar/{userId}")
    @GlobalInterceptor(checkParam = true)
    public void getAvatar(HttpServletResponse response, @VerifyParam(require = true) @PathVariable("userId") String userId) {
        File file = new File(appConfig.getAvatarPath());
        if (!file.exists()) {
            file.mkdirs();
        }
        String avatarPath = appConfig.getAvatarPath() + userId + ".jpg";
        File avatarPathFile = new File(avatarPath);
        if (!avatarPathFile.exists()) {
            avatarPath = appConfig.getAvatarPath() + "default_avatar.jpg";
        }
        try (
                FileInputStream fis = new FileInputStream(avatarPath);
                BufferedInputStream bis = new BufferedInputStream(fis);
                ServletOutputStream ots = response.getOutputStream();
                BufferedOutputStream bts = new BufferedOutputStream(ots);
        ) {
            byte[] bytes = new byte[1024];
            while (bis.read(bytes) != -1) {
                bts.write(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/getUseSpace")
    @GlobalInterceptor()
    public Result getUseSpace() {
        return userService.getUseSpace();
    }

    @PostMapping("/updateUserAvatar")
    @GlobalInterceptor()
    public void updateUserAvatar(MultipartFile avatarFile) {
        LoginUserVo loginUserVo = ServletUtils.getUser();
        File targetFile = new File(appConfig.getAvatarPath());
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            avatarFile.transferTo(new File(targetFile.getPath() + loginUserVo.getUserId() + ".jpg"));
        } catch (Exception e) {
            logger.error("上传头像失败", e);
        }
        User user = new User();
        user.setQqAvatar("");
        userService.update(user, new UpdateWrapper<User>().lambda().eq(User::getUserId, loginUserVo.getUserId()));
    }
}
